今天我們來稍微詳細一點講一下class
class abc:
def __init__(self,var1,var2...):
self.var_1=var1
self.var_2=var2
self.xxxx=xxxx
....
def addition(self):
K=self.var_1+self.var_2
return K
def disply(self):
peint(sekf.K)
return
self
somethong.var_1
。當然,self.var_1=var1
是指把self中var_1這個屬性指定var1這個值,self.function()
是指當__init__
下面一樣我們來說明一個實例
class abc:
def __init__(self,var1=0,var2=0): #可以先給參數預設值
self.var_1=var1
self.var_2=var2
def addition(self):
K=self.var_1+self.var_2
return K
def disply(self):
print(self.addition())
return
k=abc(10,12)
k.disply() #output:22
回到昨天的作業,實際上我們可以這樣來實踐:
class Rectangle:
def __init__(self,l=0,b=0,cost=0): #可以先給參數預設值
self.length=l
self.breadth=b
self.unit_cost=cost
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 200 cm, length = 400 cm, 1 cm^2 cost=200
r = Rectangle(400,200,200)
#r.length = 400 r.breadth = 200 r.unit_cost = 200
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: %s " %(r.calculate_cost()))
#Area of Rectangle: 80000 cm^2
#Cost of rectangular field: 16000000